import React, { Context } from 'react'

import { savedFileLocation, reddirtoString, chokidarFun, indexof } from './util'
import fileHelper from './fileHelper'
export let initialState = {
    fileIndex: [],
    savedFileLocation: savedFileLocation,
    reddirto: reddirtoString(savedFileLocation)
}
export type IinitialState = typeof initialState
interface Iaction {
    type: string,
    [s: string]: any
}
type Idispatch = (value: Iaction) => void
export const Then: Context<{ state: typeof initialState, dispatch: Idispatch }> = React.createContext({ state: initialState, dispatch: (Iaction: Iaction) => { } });
export const reducer = (state = initialState, action: Iaction): typeof initialState => {
    switch (action.type) {
        case 'folderDrop_down':
            {

                let index = action.res.index.split("_")
                let res = indexof(index, state.reddirto)
                res.drop_down = !res.drop_down
                return { ...state }
            }
        case 'fileDrop_down': {
            let index = action.res.index.split("_")
            let res = indexof([...index], state.reddirto)
            res.drop_down = true
            if (state.fileIndex.length !== 0) {
                console.log(11, state.fileIndex)
                let res = indexof(state.fileIndex, state.reddirto)
                res.drop_down = false
            }
            if (state.fileIndex.toString() === index.toString()) {
                state.fileIndex = []
            } else {
                state.fileIndex = index
            }
            return { ...state }
        }
        case 'deleteFile': {
            let index = action.index
            if (index.length == 1) {
                state.reddirto.splice(index[0], 1)
            } else {
                let res = indexof([...index], state.reddirto, 2)
                console.log(res)
                res.child?.splice(index[index.length - 1], 1)
            }
            return { ...state }
        }
        default:
            return state;
    }//DELETE_CONTRACT

}
interface Iprops {
    store: any,
    children: React.ReactElement
}
export default function Provider(props: Iprops) {
    return (
        <Then.Provider value={props.store}>
            {props.children}
        </Then.Provider>
    )
}